<?php

namespace app\admin\controller\yunfood;

use addons\yunfood\library\Backend;
use addons\yunfood\library\Super;
use app\admin\model\yunfood\FundUser;
use app\admin\model\yunfood\Order;
use app\admin\model\yunfood\Food;
use app\admin\model\yunfood\Shop;
use app\admin\model\yunfood\ShopDesk;
use app\admin\model\yunfood\SysUser;
use think\Db;

/**
 * 数据概览
 */
class Dashboard extends Backend
{
    /**
     * 查看
     */
    public function index()
    {
        try {
            Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {
        }

        $this->view->assign([
            'userCount'     => SysUser::count(),
            'fundUserCount' => FundUser::count(),
            'goodsCount'    => Food::where($this->getShopWhere(null, 'shop_ids'))->count(),
            'orderCount'    => Order::where($this->getShopWhere())->count(),
        ]);

        return $this->view->fetch();
    }


    /**
     * 门店数据
     */
    public function shopData()
    {
        if (! $shopId = $this->request->request('shop_id')) {
            $this->error('门店ID不能为空');
        }
        if (! $shop = Shop::get($shopId)) {
            $this->error('门店不存在');
        }
        $deskList = ShopDesk::where(['shop_id' => $shop->id])->select();
        $deskList = Super::arrayGetSet($deskList, ['id', 'name'], true);

        $result = [
            'deskList' => $deskList,
        ];

        $this->success('', null, $result);
    }

    /**
     * 订单统计
     */
    public function orderStat()
    {
        if (! $date = $this->request->request('date')) {
            $this->error('时间范围不能为空');
        }
        list($startDate, $endDate) = explode(' - ', $date);
        $startTime = strtotime($startDate);
        $endTime = strtotime($endDate);

        // 数据列表
        $dataList = Order::where('created_at', 'between time', [$startTime, $endTime])
            ->field('DATE_FORMAT(FROM_UNIXTIME(created_at), "%Y-%m-%d") AS date, COUNT(*) AS count')
            ->group('date')
            ->select();

        // 数据分组
        $statList = [];
        for ($time = $startTime; $time <= $endTime;) {
            $statList[date('Y-m-d', $time)] = ['amount' => 0, 'count' => 0];
            $time += 86400;
        }
        foreach ($dataList as $item) {
            $statList[$item['date']] = $item;
        }
        $result = [
            'categoryList'    => array_keys($statList),
            'orderCountList'  => array_column($statList, 'count'),
            'orderAmountList' => array_column($statList, 'amount'),
        ];

        $this->success('', null, $result);
    }

    public function add()
    {
        return;
    }

    public function edit($ids = null)
    {
        return;
    }

    public function del($ids = null)
    {
        return;
    }

    public function multi($ids = null)
    {
        return;
    }
}
